package com.tanhua.dubbo.api;


import com.itheima.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;

import java.util.List;

@DubboService
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Voice voice) {
        //保存
        mongoTemplate.save(voice);
    }

    @Override
    public Voice queryVoice() {
        TypedAggregation<?> aggregation = Aggregation.newAggregation(
                Voice.class,
                Aggregation.sample(1)  //统计返回的数据条数,必须设置在最后
        );
        AggregationResults<Voice> results = mongoTemplate.aggregate(aggregation, Voice.class);
        List<Voice> voices = results.getMappedResults();
        return voices.get(0);
    }

    @Override
    public void delete(Voice voice) {
        mongoTemplate.remove(voice);
    }
}
